﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RuleCode.Table;

namespace map.member.order
{
    public partial class Buy_Pay : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitPage();
            }
        }


        #region 辅助方法
        /// <summary>
        /// 初始化页面信息
        /// 处理参数
        /// </summary>
        private void InitPage()
        {
            string type = Request["type"];
            string recid = Request["id"];
            if (type == null || recid == null)
            {
                MessageBox.ShowAndRedirect(this.Page, "对不起，您没有权限访问此页面!", ResolveUrl("~/default.aspx"));
            }

            string tradeFilter = string.Empty;
            //下订单付款
            if (type == "0")
            {
                PayTypeSpan.InnerHtml =  Pay_Type .OrderPrePay ;
                InformationSpan.InnerHtml = "在您确认之后，您当前订单的资金将被冻结！";
                NickTypeSpan.InnerHtml = "卖家昵称";
                ItemBuyerNickSpan.Visible = false;
                ItemSellerNickSpan.Visible = true;
                tradeFilter = " recid = " + recid + " and taobaostatus='" + TRADE_STATUS.Buyer_Order + "'";
            }  
            //收货确认付款
            else if (type == "1")
            {
                PayTypeSpan.InnerHtml = Pay_Type.OrderFinalPay ;
                InformationSpan.InnerHtml = "在您确认之后，您当前订单的冻结的资金将被打入卖家账户！";
                NickTypeSpan.InnerHtml = "卖家昵称";
                ItemBuyerNickSpan.Visible = false;
                ItemSellerNickSpan.Visible = true;
                tradeFilter = " recid = " + recid + "   and taobaostatus = '" + TRADE_STATUS.Buyer_Recieved + "' and cbtrantype!='" + TRADE_TranType.PostBySelf + "'";
            }

            //同意卖家退款
            else if (type == "2")
            {
                PayTypeSpan.InnerHtml = Pay_Type.DegreeRefund ;
                InformationSpan.InnerHtml = "在您确认之后，您当前订单的冻结的资金将被退回买家账户！";
                NickTypeSpan.InnerHtml = "买家昵称";
                ItemBuyerNickSpan.Visible = true;
                ItemSellerNickSpan.Visible = false;
                tradeFilter = " recid = " + recid + " and taobaostatus='" + TRADE_STATUS.Seller_Refunding + "'";
            }

            if (type == "0" || type == "1" || type == "2")
            {
                taobaotrade trade = taobaotrade.Find(tradeFilter);
                if (trade.Count > 0)
                {
                    ItemBuyCountSpan.InnerHtml = trade.taobaonum.Value.ToString();
                    ItemImg.Src = trade.taobaopic_path.Value;
                    ItemNameSpan.InnerHtml = trade.taobaoname.Value;
                    ItemOrderTimeSpan.InnerHtml = trade.taobaocreated.Value;
                    ItemPaymentSpan.InnerHtml = trade.taobaopayment.Value;
                    ItemSellerNickSpan.InnerHtml = trade.seller_nick.Value;
                    ItemSinglePriceSpan.InnerHtml = trade.taobaoprice.Value;
                    ItemPostFeeSpan.InnerHtml = trade.transfee.Value;
                    ItemPostTypeSpan.InnerHtml = trade.cbtrantype.Value;
                    ItemOrderStatusSpan.InnerHtml = trade.taobaostatus.Value;
                    ItemBuyerNickSpan.InnerHtml = trade.buyer_nick.Value; 
                    return;
                }   
            }


            MessageBox.ShowAndRedirect(this.Page, "对不起，您没有权限访问此页面!", ResolveUrl("~/default.aspx"));
        }

        private bool HandleCommit()
        {
            string type = Request["type"];
            string recid = Request["id"];
            if (type == "0")
            {
                if(  HandlePrePay(type ,recid ))
                   return true ;
            }
            else if (type == "1")
            {
                if( HandleFinalPay(type, recid))
                   return true ;
            }
            else if (type == "2")
            {
                if (HandleRefund(type, recid))
                    return true;
            }

            MessageBox.ShowAndRedirect(this.Page, "对不起，您没有权限访问此页面!", ResolveUrl("~/default.aspx"));
            return false;
        }


        /// <summary>
        /// 处理退款
        /// </summary>
        /// <param name="type"></param>
        /// <param name="recid"></param>
        /// <returns></returns>
        private bool HandleRefund(string type, string recid)
        {
            if (type == "2")
            {
                taobaotrade ui = taobaotrade.Find(" recid = " + recid + " and taobaostatus='" + TRADE_STATUS.Seller_Refunding + "'");
                cbuser sellerUser = cbuser.Find(" cbuserid = '" + AliApi.appUserId + "'");
                cbuser buyerUser = cbuser.Find("cbuserid='" + ui.buyer_nick.Value + "'");
                if (ui.Count <= 0 || sellerUser.Count <= 0 || buyerUser.Count <= 0)
                { 
                    MessageBox.ShowAndRedirect(this.Page, "对不起，您没有权限访问此页面！", ResolveUrl("~/default.aspx"));
                    return false;
                }

                double need = zfunction.str2double(ui.taobaopayment.ToString());
                cbmoneytrans mt = cbmoneytrans.Find("1=2");
                mt.New();
                mt.cbuserid.Value = ui.seller_nick.Value;
                mt.cbmoney.Value = -need;
                mt.cbmoneytrantype.Value = MONEY_TransType.UnBlock;
                mt.jccreatedate.Value = DateTime.Now;
                mt.jccreatetime.StringValue = DateTime.Now.ToLongTimeString();
                mt.jcdesc.Value = ui.RECID.ToString() + " " + ui.taobaoname.ToString();
                mt.NoYes_dongjie.Value = RuleCode.Enum.NoYes.No;
                mt.RefTable.Value = "taobaotrade";
                mt.RefRecID.Value = recid;
                mt.Insert();
                sellerUser.cbmoneyD.Value -= need;
                sellerUser.Modify();

                cbmoneytrans mt2 = cbmoneytrans.Find("1=2");
                mt2.New();
                mt2.cbuserid.Value = ui.buyer_nick.ToString();
                mt2.cbmoney.Value = need;
                mt2.cbmoneytrantype.Value = MONEY_TransType.Refund;
                mt2.jccreatedate.Value = DateTime.Now;
                mt2.jccreatetime.StringValue = DateTime.Now.ToLongTimeString();
                mt2.jcdesc.Value = ui.RECID.ToString() + " " + ui.taobaoname.ToString();
                mt2.NoYes_dongjie.Value = RuleCode.Enum.NoYes.No;
                mt.RefTable.Value = "taobaotrade";
                mt.RefRecID.Value = recid;
                mt2.Insert();

                buyerUser.cbmoney.Value = buyerUser.cbmoney.Value + need;
                buyerUser.cbmoneyZ.Value = buyerUser.cbmoneyZ.Value + need;
                buyerUser.Modify();

                ui.taobaostatus.Value = TRADE_STATUS.Trade_Closed;
                ui.Modify();

                MessageBox.ShowAndRedirect(this.Page, "退款成功", ResolveUrl("~/member/order/sell_13.aspx"));
                return true;
            }
            return false;
        }

         /// <summary>
         /// 订单付款
         /// </summary>
         /// <param name="type">类型</param>
         /// <param name="recid">交易recid</param>
        private bool HandlePrePay(string type, string recid)
        {
            if (type == "0")
            {
                taobaotrade ui = taobaotrade.Find(" recid = " + recid+" and taobaostatus='"+TRADE_STATUS.Buyer_Order +"'");
                if (ui.Count > 0)
                {
                    cbuser u = cbuser.u();
                    double need = zfunction.str2double(ui.taobaopayment.ToString());
                    double have = zfunction.str2double(u.cbmoney.ToString());
                    if (have < need)
                    {
                        MessageBox.ShowAndRedirect(this.Page, "你的余额不够,请您先充值！", ResolveUrl("~/member/money/chongzhi.aspx"));
                        return false ;
                    }
                    if (ui.taobaostatus.ToString() != TRADE_STATUS.Buyer_Order)
                    {
                        MessageBox.Show(this.Page, "该订单已经支付,无需再付款,操作取消.");
                        return false ;
                    }
                    cbmoneytrans mt = cbmoneytrans.Find("1=2");
                    mt.New();
                    mt.cbuserid.Value = ui.buyer_nick.ToString();
                    mt.cbmoney.Value = -need;
                    mt.cbmoneytrantype.Value = MONEY_TransType.BuyOut;
                    mt.jccreatedate.Value = DateTime.Now;
                    mt.jccreatetime.StringValue = DateTime.Now.ToLongTimeString();
                    mt.jcdesc.Value = ui.RECID.ToString() + " " + ui.taobaoname.ToString();
                    mt.NoYes_dongjie.Value = RuleCode.Enum.NoYes.No;
                    mt.RefTable.Value = "taobaotrade";
                    mt.RefRecID.Value = recid;
                    mt.Insert();
                    u.cbmoney.Value = u.cbmoney.Value - need;
                    u.cbmoneyF.Value = u.cbmoneyF.Value - need;
                    u.Modify();

                    cbmoneytrans mt2 = cbmoneytrans.Find("1=2");
                    mt2.New();
                    mt2.cbuserid.Value = ui.seller_nick.ToString();
                    mt2.cbmoney.Value = need;
                    mt2.cbmoneytrantype.Value = MONEY_TransType.Block;
                    mt2.jccreatedate.Value = DateTime.Now;
                    mt2.jccreatetime.StringValue = DateTime.Now.ToLongTimeString();
                    mt2.jcdesc.Value = ui.RECID.ToString() + " " + ui.taobaoname.ToString();
                    mt2.NoYes_dongjie.Value = RuleCode.Enum.NoYes.Yes;
                    mt.RefTable.Value = "taobaotrade";
                    mt.RefRecID.Value = recid;
                    mt2.Insert();

                    cbuser u2 = cbuser.Find(" cbuserid = '" + ui.seller_nick.ToString() + "'");
                    u2.cbmoneyD.Value += need;
                    u2.Modify();


                    ui.taobaostatus.Value = TRADE_STATUS.Buyer_Pay;
                    ui.Modify();
                    MessageBox.ShowAndRedirect(this.Page, "恭喜您，付款：" + need.ToString() + "元成功！", ResolveUrl("~/member/order/buy_3.aspx"));
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 订单已收货，确认付款
        /// </summary>
        /// <param name="type"></param>
        /// <param name="recid"></param>
        private bool HandleFinalPay(string type, string recid)
        {
            if (type == "1")
            {
                taobaotrade ui = taobaotrade.Find(" recid = " + recid + "   and taobaostatus = '" + TRADE_STATUS.Buyer_Recieved + "' and cbtrantype!='" + TRADE_TranType.PostBySelf + "'");
                cbuser u2 = cbuser.Find(" cbuserid = '" + ui.seller_nick.ToString() + "'");

                if (ui.Count < 0 || u2.Count < 0)
                {
                    MessageBox.ShowAndRedirect(this.Page, "对不起，您没有权限访问此页面", ResolveUrl("~/default.aspx"));
                    return false ;
                }
                double need = zfunction.str2double(ui.taobaopayment.ToString());
                cbmoneytrans mt = cbmoneytrans.Find("1=2");
                mt.New();
                mt.cbuserid.Value = ui.seller_nick.Value;
                mt.cbmoney.Value = -need;
                mt.cbmoneytrantype.Value = MONEY_TransType.UnBlock;
                mt.jccreatedate.Value = DateTime.Now;
                mt.jccreatetime.StringValue = DateTime.Now.ToLongTimeString();
                mt.jcdesc.Value = ui.RECID.ToString() + " " + ui.taobaoname.ToString();
                mt.NoYes_dongjie.Value = RuleCode.Enum.NoYes.No;
                mt.RefTable.Value = "taobaotrade";
                mt.RefRecID.Value = recid;
                mt.Insert();
                u2.cbmoneyD.Value -= need;

                cbmoneytrans mt2 = cbmoneytrans.Find("1=2");
                mt2.New();
                mt2.cbuserid.Value = ui.seller_nick.ToString();
                mt2.cbmoney.Value = need;
                mt2.cbmoneytrantype.Value = MONEY_TransType.SaleIn;
                mt2.jccreatedate.Value = DateTime.Now;
                mt2.jccreatetime.StringValue = DateTime.Now.ToLongTimeString();
                mt2.jcdesc.Value = ui.RECID.ToString() + " " + ui.taobaoname.ToString();
                mt2.NoYes_dongjie.Value = RuleCode.Enum.NoYes.No;
                mt.RefTable.Value = "taobaotrade";
                mt.RefRecID.Value = recid;
                mt2.Insert();
                u2.cbmoney.Value = u2.cbmoney.Value + need;
                u2.cbmoneyZ.Value = u2.cbmoneyZ.Value + need;
                //u2.cbmoneyD.Value = need;
                u2.Modify();


                ui.taobaostatus.Value = TRADE_STATUS.Trade_Finished;
                ui.Modify();
                MessageBox.ShowAndRedirect(this.Page, "操作成功，交易金额:" + need.ToString() + "已转入卖家账户中！", ResolveUrl("~/member/order/buy_9.aspx"));
                return true;
            }
            return false;
        }
        #endregion

        #region 按钮事件响应
        protected void ConfirmButton_Click(object sender, EventArgs e)
        {
            bool passResult = cbuser.ValidatePassword(AliApi.appUserId, PasswordInput.Value);
            if (passResult == true)
            {
                HandleCommit();
            }
            else
            {
                MessageBox.Show(this.Page,"对不起，密码不正确！");
            }
        }
        #endregion
    }
}
